<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 增减购物车信息
 *
 * @author      Eden
 * @datetime    2016/12/18 23:18
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Buy_Model extends API_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {

            if (!$this->checkParams($params)) {
                $send['error'] = $this->getError();
                break;
            }

            $where = array(
                'userId' => $params['userId'],
                'goodsId' => $params['goodsId'],
                'ruleId' => $params['ruleId'],
            );

            $db = clone($this->db);
            $q = $db->get_where('user_car', $where);
            $row = $q->row_array();

            $db2 = clone($this->db);
            $db2->where('userId', $params['userId']);
            $db2->update('user_car', ['selected' => 0]);

            if (empty($row)) {
                $data = array_merge($where, array(
                    'num' => intval($params['num']),
                    'created' => dateTime(),
                    'selected' => 1
                ));
                $this->db->insert('user_car', $data);
                $affect = $this->db->insert_id();
            } else {
                $data = array(
                    'num' => intval($params['num']),
                    'selected' => 1
                );
                $this->db->where($where)->update('user_car', $data);
                $affect = $this->db->affected_rows();
            }

            if ($affect) {
                $send['state'] = true;
                $send['data'] = array(
                    'msg' => '操作成功'
                );
            } else {
                $send['error'] = '操作失败';
            }
        } while(false);
        $this->output->send($send);
    }

    /**
     * 检查参数
     * @param array $params
     * @return bool
     */
    private function checkParams($params = array())
    {

        if ($this->input->method(true) !== 'POST') {
            $this->setError('非法请求');
            return false;
        }

        if (empty($params['userId']) || empty($params['goodsId']) || empty($params['num']) || empty($params['ruleId'])) {
            $this->setError('参数错误');
            return false;
        }

        return true;
    }

}
